import tkinter as tk
from tkinter import ttk, messagebox
import customtkinter
from ui.pages.scrollable_page import ScrollablePage
from core.services.data_manager import DataManager
from core.models.order import Order, OrderStatus
from core.utils.i18n import t
from ui.styles.theme import Theme
from core.utils.logger import info, error
import os
import json
from datetime import datetime


class OrdersPage(ScrollablePage):
    """Page to show historical orders. If a user is logged in, shows only that user's orders; otherwise shows all."""
    
    def _get_product_name_en(self, product_id):
        """获取商品的英文名称"""
        try:
            product = self.controller.product_service.get_product_by_id(product_id)
            if product:
                # 使用get_display_name方法或name_en属性
                if hasattr(product, 'get_display_name'):
                    return product.get_display_name()
                elif hasattr(product, 'name_en') and product.name_en:
                    return product.name_en
                else:
                    # 从JSON数据中直接读取name_en
                    from core.services.data_manager import DataManager
                    dm = DataManager()
                    products_data = dm.load_products()
                    for p_data in products_data:
                        if p_data.get('product_id') == product_id:
                            return p_data.get('name_en') or p_data.get('name', '')
            return None
        except Exception:
            return None

    def create_widgets(self):
        content = self.scrollable_frame

        # 初始化批量删除模式状态变量
        self.batch_delete_mode = False
        self.selected_orders = set()

        # 获取主题颜色
        fg_primary = Theme.get_color('fg_primary')
        accent_color = Theme.get_color('accent')

        # Header
        header_frame = ttk.Frame(content, padding=8)
        header_frame.pack(fill='x')
        
        # 返回按钮
        back_btn = customtkinter.CTkButton(
            header_frame, 
            text=t('orders.back'), 
            width=80,
            command=lambda: self.controller.show_page('ProductPage')
        )
        back_btn.pack(side='left', padx=(0, 8))
        
        # 标题
        title_label = customtkinter.CTkLabel(
            header_frame, 
            text=t('orders.title'), 
            font=('Arial', 18, 'bold'),
            text_color=fg_primary
        )
        title_label.pack(side='left')

        # container for order cards
        self.orders_container = ttk.Frame(content)
        self.orders_container.pack(fill='both', expand=True, padx=12, pady=(8, 20))

        # bottom: footer with buttons
        self.footer = ttk.Frame(content)
        self.footer.pack(fill='x', padx=12, pady=(0, 12))
        
        refresh_btn = customtkinter.CTkButton(
            self.footer, 
            text=t('orders.refresh'), 
            width=100,
            command=self.update_data
        )
        refresh_btn.pack(side='left', padx=(0, 8))
        
        export_btn = customtkinter.CTkButton(
            self.footer, 
            text=t('orders.export'), 
            width=100,
            command=self._export_all
        )
        export_btn.pack(side='left', padx=(0, 8))
        
        # 刷新库存按钮
        refresh_stock_btn = customtkinter.CTkButton(
            self.footer, 
            text=t('orders.refresh_stock'), 
            width=120,
            fg_color='#16a085',
            hover_color='#138D75',
            command=self._refresh_stock_display
        )
        refresh_stock_btn.pack(side='left', padx=(0, 8))
        
        # 批量删除按钮
        self.batch_delete_btn = customtkinter.CTkButton(
            self.footer, 
            text=t('orders.batch_delete.enter_mode'), 
            width=120,
            fg_color='#e74c3c',
            hover_color='#c0392b',
            command=self._toggle_batch_delete_mode
        )
        self.batch_delete_btn.pack(side='left', padx=(0, 8))

    def _render_order(self, parent, order, index=None):
        # card-like frame - 使用 ttk 保持兼容性
        frame = ttk.Frame(parent, padding=10)
        frame.pack(fill='x', pady=6)

        # 获取订单ID
        if isinstance(order, Order):
            order_id = order.order_id
        else:
            order_id = order.get('order_id', order.get('id', f'#{index if index is not None else "?"}'))

        # 如果是批量删除模式，添加复选框
        if self.batch_delete_mode:
            # 创建包含复选框的容器
            checkbox_frame = ttk.Frame(frame)
            checkbox_frame.pack(fill='x', pady=(0, 5))
            
            # 复选框
            checkbox_var = tk.BooleanVar()
            checkbox_var.set(order_id in self.selected_orders)
            
            def on_checkbox_change():
                if checkbox_var.get():
                    self.selected_orders.add(order_id)
                else:
                    self.selected_orders.discard(order_id)
                self._update_selection_display()
            
            checkbox = ttk.Checkbutton(
                checkbox_frame, 
                variable=checkbox_var,
                command=on_checkbox_change,
                text=t('orders.batch_delete.select_order', order_id=order_id)
            )
            checkbox.pack(side='left', padx=(0, 10))
            
            # 添加视觉分隔线
            ttk.Separator(checkbox_frame, orient='horizontal').pack(fill='x', pady=(5, 0))

        # header: order id, status and time
        header = ttk.Frame(frame)
        header.pack(fill='x')
        
        # 如果是 Order 对象，直接使用属性；否则从字典获取
        if isinstance(order, Order):
            created = order.created_at
            status_text = order.get_status_display()
            status_color = order.get_status_color()
        else:
            created = order.get('created_at') or order.get('created') or order.get('timestamp')
            status = order.get('status', 'pending')
            order_obj = Order.from_dict(order)
            status_text = order_obj.get_status_display()
            status_color = order_obj.get_status_color()
        
        try:
            # try to parse ISO timestamp for nicer formatting
            if created:
                dt = datetime.fromisoformat(created)
                created_str = dt.strftime('%Y-%m-%d %H:%M:%S')
            else:
                created_str = ''
        except Exception:
            created_str = str(created)

        # 订单ID
        ttk.Label(
            header, 
            text=f'Order: {order_id}', 
            font=('Arial', 12, 'bold')
        ).pack(side='left')
        
        # 订单状态
        ttk.Label(
            header, 
            text=f'[{status_text}]', 
            font=('Arial', 10, 'bold'),
            foreground=status_color
        ).pack(side='left', padx=10)
        
        # 创建时间
        ttk.Label(
            header, 
            text=created_str, 
            foreground='#666'
        ).pack(side='right')

        # body: items summary
        body = ttk.Frame(frame)
        body.pack(fill='x', pady=(8, 6))

        # 获取订单项
        if isinstance(order, Order):
            items = order.items
            total = order.total
        else:
            items = order.get('items', [])
            total = order.get('total')
        
        if not items:
            ttk.Label(
                body, 
                text='(no items recorded)', 
                foreground='#666'
            ).pack(anchor='w')
        else:
            # show up to 3 item names
            for i, it in enumerate(items[:3]):
                if isinstance(order, Order):
                    # 使用英文商品名称
                    product_id = it.product_id
                    name = self._get_product_name_en(product_id) or it.product_name
                    qty = it.quantity
                else:
                    product_id = it.get('product_id', '')
                    name = self._get_product_name_en(product_id) if product_id else it.get('name') or it.get('product_id') or str(it)
                    qty = it.get('quantity')
                
                if qty is not None:
                    ttk.Label(
                        body, 
                        text=f'• {name}  x{qty}'
                    ).pack(anchor='w')
                else:
                    ttk.Label(
                        body, 
                        text=f'• {name}'
                    ).pack(anchor='w')
            if len(items) > 3:
                ttk.Label(
                    body, 
                    text=f'… and {len(items)-3} more', 
                    foreground='#666'
                ).pack(anchor='w')

        # footer: total and actions
        ftr = ttk.Frame(frame)
        ftr.pack(fill='x')
        
        # 总价
        ttk.Label(
            ftr, 
            text=f'Total: ¥{total:.2f}' if isinstance(total, (int, float)) else f'Total: {total}', 
            font=('Arial', 11, 'bold')
        ).pack(side='left')
        
        # 操作按钮容器
        actions = ttk.Frame(ftr)
        actions.pack(side='right')
        
        # View 按钮
        view_btn = customtkinter.CTkButton(
            actions, 
            text='View', 
            width=60,
            height=28,
            command=lambda o=order: self._view_order_detail(o)
        )
        view_btn.pack(side='left', padx=3)
        
        # Re-order 按钮
        reorder_btn = customtkinter.CTkButton(
            actions, 
            text='Re-order', 
            width=80,
            height=28,
            command=lambda o=order: self._reorder(o)
        )
        reorder_btn.pack(side='left', padx=3)
        
        # 根据订单状态动态显示操作按钮
        if isinstance(order, Order):
            # 支付按钮（仅待支付状态）
            if order.can_pay():
                pay_btn = customtkinter.CTkButton(
                    actions, 
                    text='💳 Pay', 
                    width=70,
                    height=28,
                    fg_color='#16a085',
                    hover_color='#138D75',
                    command=lambda o=order: self._pay_order(o)
                )
                pay_btn.pack(side='left', padx=3)
            
            # 评价按钮（所有状态都可以评价，除了已取消的订单）
            # 允许多次评价，所以不检查是否已评价
            if order.status != OrderStatus.CANCELLED:
                review_btn = customtkinter.CTkButton(
                    actions, 
                    text='⭐ Review', 
                    width=70,
                    height=28,
                    fg_color='#16a085',
                    hover_color='#138D75',
                    command=lambda o=order: self._review_order(o)
                )
                review_btn.pack(side='left', padx=3)
            
            # 完成按钮（仅已发货状态）
            if order.can_complete():
                complete_btn = customtkinter.CTkButton(
                    actions, 
                    text='✅ Complete', 
                    width=100,
                    height=28,
                    fg_color='#16a085',
                    hover_color='#138D75',
                    command=lambda o=order: self._complete_order(o)
                )
                complete_btn.pack(side='left', padx=3)
            
            # 取消按钮（待支付或已支付状态）
            if order.can_cancel():
                cancel_btn = customtkinter.CTkButton(
                    actions, 
                    text='Cancel', 
                    width=70,
                    height=28,
                    fg_color='#f39c12',
                    hover_color='#e67e22',
                    command=lambda o=order: self._cancel_order(o)
                )
                cancel_btn.pack(side='left', padx=3)
            
            # 删除按钮（仅已取消或已完成状态）
            if order.can_delete():
                delete_btn = customtkinter.CTkButton(
                    actions, 
                    text='🗑️ Delete', 
                    width=70,
                    height=28,
                    fg_color='#e74c3c',
                    hover_color='#c0392b',
                    command=lambda o=order: self._delete_order(o)
                )
                delete_btn.pack(side='left', padx=3)

    def _view_order_detail(self, order):
        # 转换为 Order 对象（如果还不是）
        if not isinstance(order, Order):
            order = Order.from_dict(order)
        
        win = tk.Toplevel(self)
        win.title(f"Order Details - {order.order_id}")
        # 根据商品数量调整窗口高度，最多显示6个商品卡片
        item_count = len(order.items)
        base_height = 450
        item_height = 80
        max_items = 6
        height = base_height + min(item_count, max_items) * item_height
        win.geometry(f'700x{min(height, 800)}')
        win.resizable(True, True)
        
        # 主框架 - 使用 CustomTkinter
        main_frm = customtkinter.CTkFrame(win)
        main_frm.pack(fill='both', expand=True, padx=15, pady=15)
        
        # 标题
        title_frm = customtkinter.CTkFrame(main_frm, fg_color="transparent")
        title_frm.pack(fill='x', pady=(0, 15))
        customtkinter.CTkLabel(
            title_frm, 
            text='📋 Order Details', 
            font=('Arial', 18, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(anchor='w')
        
        # 分隔线
        customtkinter.CTkFrame(main_frm, height=2, fg_color=Theme.get_color('border_color')).pack(fill='x', pady=(0, 15))
        
        # 订单基本信息框架 - 使用自定义样式
        info_frm = customtkinter.CTkFrame(main_frm, fg_color=("gray95", "gray20"))
        info_frm.pack(fill='x', pady=10, padx=0, ipadx=15, ipady=15)
        
        # 区域标题
        customtkinter.CTkLabel(
            info_frm, 
            text='📌 Basic Information', 
            font=('Arial', 12, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(anchor='w', pady=(0, 10))
        
        # 订单号
        order_id_frm = customtkinter.CTkFrame(info_frm, fg_color="transparent")
        order_id_frm.pack(fill='x', pady=3)
        customtkinter.CTkLabel(
            order_id_frm, 
            text='Order ID:', 
            font=('Arial', 10, 'bold'), 
            width=80,
            anchor='w'
        ).pack(side='left')
        customtkinter.CTkLabel(
            order_id_frm, 
            text=order.order_id, 
            font=('Arial', 10)
        ).pack(side='left')
        
        # 订单状态
        status_frm = customtkinter.CTkFrame(info_frm, fg_color="transparent")
        status_frm.pack(fill='x', pady=3)
        customtkinter.CTkLabel(
            status_frm, 
            text='Status:', 
            font=('Arial', 10, 'bold'), 
            width=80,
            anchor='w'
        ).pack(side='left')
        customtkinter.CTkLabel(
            status_frm, 
            text=order.get_status_display(), 
            font=('Arial', 10, 'bold'), 
            text_color=order.get_status_color()
        ).pack(side='left')
        
        # 创建时间
        created_frm = customtkinter.CTkFrame(info_frm, fg_color="transparent")
        created_frm.pack(fill='x', pady=3)
        customtkinter.CTkLabel(
            created_frm, 
            text='Created At:', 
            font=('Arial', 10, 'bold'), 
            width=80,
            anchor='w'
        ).pack(side='left')
        try:
            dt = datetime.fromisoformat(order.created_at)
            created_str = dt.strftime('%Y-%m-%d %H:%M:%S')
        except:
            created_str = order.created_at
        customtkinter.CTkLabel(
            created_frm, 
            text=created_str, 
            font=('Arial', 10)
        ).pack(side='left')
        
        # 更新时间
        updated_frm = customtkinter.CTkFrame(info_frm, fg_color="transparent")
        updated_frm.pack(fill='x', pady=3)
        customtkinter.CTkLabel(
            updated_frm, 
            text='Updated At:', 
            font=('Arial', 10, 'bold'), 
            width=80,
            anchor='w'
        ).pack(side='left')
        try:
            dt = datetime.fromisoformat(order.updated_at)
            updated_str = dt.strftime('%Y-%m-%d %H:%M:%S')
        except:
            updated_str = order.updated_at
        customtkinter.CTkLabel(
            updated_frm, 
            text=updated_str, 
            font=('Arial', 10)
        ).pack(side='left')
        
        # 商品清单框架
        items_frm = customtkinter.CTkFrame(main_frm, fg_color=("gray95", "gray20"))
        items_frm.pack(fill='both', expand=True, pady=10, padx=0, ipadx=15, ipady=15)
        
        # 区域标题
        customtkinter.CTkLabel(
            items_frm, 
            text='🛒 Product List', 
            font=('Arial', 12, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(anchor='w', pady=(0, 10))
        
        # 创建商品列表容器
        items_container = customtkinter.CTkFrame(items_frm, fg_color="transparent")
        items_container.pack(fill='both', expand=True)
        
        # 显示商品信息 - 使用 Label 直接显示，无需滚动条
        for idx, item in enumerate(order.items, 1):
            # 商品卡片
            item_card = customtkinter.CTkFrame(items_container, fg_color=("gray97", "gray22"))
            item_card.pack(fill='x', pady=5)
            
            # 商品名和序号
            name_frame = customtkinter.CTkFrame(item_card, fg_color="transparent")
            name_frame.pack(fill='x', pady=(10, 5), padx=10)
            customtkinter.CTkLabel(
                name_frame,
                text=f'{idx}. {self._get_product_name_en(item.product_id) or item.product_name}',
                font=('Arial', 11, 'bold'),
                text_color=Theme.get_color('fg_primary')
            ).pack(side='left')
            
            # 商品详情
            detail_frame = customtkinter.CTkFrame(item_card, fg_color="transparent")
            detail_frame.pack(fill='x', padx=10, pady=(0, 10))
            
            # 数量和单价
            customtkinter.CTkLabel(
                detail_frame,
                text=f'Quantity: {item.quantity}',
                font=('Arial', 10),
                text_color=Theme.get_color('fg_secondary')
            ).pack(side='left')
            
            customtkinter.CTkLabel(
                detail_frame,
                text=f'Price: ¥{item.price:.2f}',
                font=('Arial', 10),
                text_color=Theme.get_color('fg_secondary')
            ).pack(side='left', padx=(20, 0))
            
            customtkinter.CTkLabel(
                detail_frame,
                text=f'Subtotal: ¥{item.subtotal:.2f}',
                font=('Arial', 10, 'bold'),
                text_color='#27AE60'
            ).pack(side='right')
        
        # 总金额框架
        total_frm = customtkinter.CTkFrame(main_frm, fg_color="transparent")
        total_frm.pack(fill='x', pady=10)
        
        customtkinter.CTkFrame(total_frm, height=2, fg_color=Theme.get_color('border_color')).pack(fill='x', pady=(0, 15))
        
        total_info = customtkinter.CTkFrame(total_frm, fg_color="transparent")
        total_info.pack(fill='x')
        customtkinter.CTkLabel(
            total_info, 
            text='💰 Total:', 
            font=('Arial', 12, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(side='left')
        customtkinter.CTkLabel(
            total_info, 
            text=f'¥{order.total:.2f}', 
            font=('Arial', 16, 'bold'), 
            text_color='#E74C3C'
        ).pack(side='right')
        
        # 按钮框架
        btn_frm = customtkinter.CTkFrame(main_frm, fg_color="transparent")
        btn_frm.pack(fill='x', pady=(10, 0))
        
        customtkinter.CTkButton(
            btn_frm, 
            text='✅ Close', 
            width=120,
            command=win.destroy,
            fg_color=Theme.get_color('accent'),
            hover_color=Theme.get_color('accent_hover')
        ).pack(side='right')

    def _reorder(self, order):
        # 转换为 Order 对象（如果还不是）
        if not isinstance(order, Order):
            order = Order.from_dict(order)
        
        # simple: add items back to shopping cart
        try:
            for item in order.items:
                pid = item.product_id
                qty = item.quantity
                # try to find product
                try:
                    product = None
                    for p in self.controller.product_service.get_all_products():
                        if getattr(p, 'product_id', None) == pid:
                            product = p
                            break
                    if product:
                        self.controller.shopping_cart.add_item(product, qty)
                    else:
                        # cannot find product; ignore
                        pass
                except Exception:
                    pass
            messagebox.showinfo('Re-order', 'Items added to cart')
            # update cart display if product page exists
            try:
                pg = self.controller.pages.get('ProductPage')
                if hasattr(pg, 'update_cart_display'):
                    pg.update_cart_display()
            except Exception:
                pass
        except Exception as e:
            messagebox.showerror('Re-order error', str(e))
    
    def _pay_order(self, order):
        """支付订单"""
        if not isinstance(order, Order):
            order = Order.from_dict(order)
        
        # 确认支付
        result = messagebox.askyesno(
            'Confirm Payment', 
            f'Confirm payment for order {order.order_id}?\n\nOrder Total: ¥{order.total:.2f}'
        )
        if not result:
            return
        
        # 调用 OrderService 支付订单
        try:
            success = self.controller.order_service.pay_order(order.order_id)
            if success:
                messagebox.showinfo('Payment Successful', f'Order {order.order_id} payment successful!\n\nYour order will be shipped as soon as possible.')
                self.update_data()  # 刷新页面
            else:
                messagebox.showerror('Payment Failed', 'Order payment failed, please try again')
        except Exception as e:
            messagebox.showerror('Payment Failed', f'Error occurred during payment: {e}')
    
    def _check_order_reviewed(self, order):
        """检查订单是否已评价"""
        if not self.controller.auth_service.is_logged_in():
            return False
        
        try:
            user_id = self.controller.auth_service.current_user.user_id
            # 检查订单中的所有商品是否都已评价
            for item in order.items:
                review = self.controller.review_service.get_user_product_review(user_id, item.product_id)
                if not review:
                    return False
            return True
        except Exception as e:
            from core.utils.logger import error
            error(f"检查订单评价状态失败: {e}")
            return False
    
    def _review_order(self, order):
        """评价订单中的商品"""
        if not isinstance(order, Order):
            order = Order.from_dict(order)
        
        if not self.controller.auth_service.is_logged_in():
            messagebox.showwarning('需要登录', '请先登录后再进行评价')
            return
        
        try:
            from ui.components.review_dialog import ReviewDialog
            
            # 为订单中的每个商品打开评价对话框
            for item in order.items:
                # 获取商品对象
                product = self.controller.product_service.get_product_by_id(item.product_id)
                if product:
                    # 打开评价对话框
                    ReviewDialog(
                        parent=self,
                        controller=self.controller,
                        product=product,
                        order=order
                    )
            
            # 注意：成功消息现在由评价对话框内部处理，这里不再显示
            # 用户完成评价后，对话框会自动显示成功消息并关闭
            self.update_data()  # 刷新页面
            
        except Exception as e:
            from core.utils.logger import error
            error(f"评价订单失败: {e}")
            messagebox.showerror('评价失败', f'评价时发生错误: {e}')
    
    def _complete_order(self, order):
        """完成订单"""
        if not isinstance(order, Order):
            order = Order.from_dict(order)
        
        # 确认完成
        result = messagebox.askyesno('Complete Order', f'Confirm complete order {order.order_id}?')
        if not result:
            return
        
        # 调用 OrderService 完成订单
        try:
            success = self.controller.order_service.complete_order(order.order_id)
            if success:
                messagebox.showinfo('Complete Successful', f'Order {order.order_id} has been completed')
                self.update_data()  # 刷新页面
            else:
                messagebox.showerror('Complete Failed', 'Failed to complete order')
        except Exception as e:
            messagebox.showerror('Complete Failed', f'Error occurred while completing order: {e}')
    
    def _cancel_order(self, order):
        """取消订单"""
        if not isinstance(order, Order):
            order = Order.from_dict(order)
        
        # 确认取消
        result = messagebox.askyesno('Cancel Order', f'Confirm cancel order {order.order_id}?')
        if not result:
            return
        
        # 调用 OrderService 取消订单
        try:
            success = self.controller.order_service.cancel_order(order.order_id)
            if success:
                messagebox.showinfo('Cancel Successful', f'Order {order.order_id} has been cancelled')
                self.update_data()  # 刷新页面
            else:
                messagebox.showerror('Cancel Failed', 'Failed to cancel order')
        except Exception as e:
            messagebox.showerror('Cancel Failed', f'Error occurred while cancelling order: {e}')
    
    def _delete_order(self, order):
        """删除订单"""
        if not isinstance(order, Order):
            order = Order.from_dict(order)
        
        # 确认删除
        result = messagebox.askyesno('Delete Order', f'Confirm delete order {order.order_id}?\n\nThis action cannot be undone!')
        if not result:
            return
        
        # 调用 OrderService 删除订单
        try:
            success = self.controller.order_service.delete_order(order.order_id)
            if success:
                messagebox.showinfo('Delete Successful', f'Order {order.order_id} has been deleted')
                self.update_data()  # 刷新页面
            else:
                messagebox.showerror('Delete Failed', 'Failed to delete order')
        except Exception as e:
            messagebox.showerror('Delete Failed', f'Error occurred while deleting order: {e}')

    def _export_all(self):
        dm = DataManager()
        orders = dm.load_data('orders.json') or []
        try:
            export_path = os.path.join(dm.data_dir, 'orders_export.json')
            with open(export_path, 'w', encoding='utf-8') as f:
                json.dump(orders, f, ensure_ascii=False, indent=2)
            messagebox.showinfo('Export', f'Exported {len(orders)} orders to {export_path}')
        except Exception as e:
            messagebox.showerror('Export error', str(e))

    def update_data(self):
        # Clear container
        for c in self.orders_container.winfo_children():
            c.destroy()

        # 使用 OrderService 获取订单
        try:
            if self.controller.auth_service.is_logged_in():
                uid = getattr(self.controller.auth_service.current_user, 'user_id', None)
                if uid:
                    user_orders = self.controller.order_service.get_user_orders(uid)
                else:
                    user_orders = self.controller.order_service.get_all_orders()
            else:
                user_orders = self.controller.order_service.get_all_orders()
        except Exception as e:
            from core.utils.logger import error
            error(f"Failed to load orders: {e}")
            # 回退到直接读取 JSON
            dm = DataManager()
            orders_data = dm.load_data('orders.json') or []
            user_orders = [Order.from_dict(o) for o in orders_data]

        if not user_orders:
            ttk.Label(
                self.orders_container, 
                text='No orders found.', 
                foreground='#666'
            ).pack(pady=40)
            return

        # render all orders (newest first - already sorted by OrderService)
        try:
            for idx, order in enumerate(user_orders):
                self._render_order(self.orders_container, order, index=idx+1)
        except Exception as e:
            from core.utils.logger import error
            error(f"Failed to render orders: {e}")
            # fallback: simple text list
            for o in user_orders:
                ttk.Label(
                    self.orders_container, 
                    text=str(o)
                ).pack(anchor='w')
    
    def _toggle_batch_delete_mode(self):
        """切换批量删除模式"""
        self.batch_delete_mode = not self.batch_delete_mode
        self.selected_orders.clear()
        
        if self.batch_delete_mode:
            self.batch_delete_btn.configure(text=t('orders.batch_delete.exit_mode'))
            self._show_batch_operation_bar()
        else:
            self.batch_delete_btn.configure(text=t('orders.batch_delete.enter_mode'))
            self._hide_batch_operation_bar()
        
        # 刷新页面显示
        self.update_data()
    
    def _show_batch_operation_bar(self):
        """显示批量操作栏"""
        # 清除footer中的现有按钮
        for widget in self.footer.winfo_children():
            if widget != self.batch_delete_btn:
                widget.pack_forget()
        
        # 添加批量操作栏
        self.batch_operation_frame = ttk.Frame(self.footer)
        self.batch_operation_frame.pack(side='left', padx=(0, 8))
        
        # 选择状态提示
        self.selection_label = customtkinter.CTkLabel(
            self.batch_operation_frame, 
            text='Selected: 0 orders'
        )
        self.selection_label.pack(side='left', padx=(0, 10))
        
        # 确认删除按钮
        self.confirm_delete_btn = customtkinter.CTkButton(
            self.batch_operation_frame, 
            text='Confirm Delete', 
            width=100,
            fg_color='#e74c3c',
            hover_color='#c0392b',
            command=self._batch_delete_orders
        )
        self.confirm_delete_btn.pack(side='left', padx=(0, 5))
        
        # 批量取消按钮
        self.confirm_cancel_btn = customtkinter.CTkButton(
            self.batch_operation_frame, 
            text='Batch Cancel', 
            width=100,
            fg_color='#f39c12',
            hover_color='#e67e22',
            command=self._batch_cancel_orders
        )
        self.confirm_cancel_btn.pack(side='left', padx=(0, 5))
        
        # 全选/取消全选按钮
        self.select_all_btn = customtkinter.CTkButton(
            self.batch_operation_frame, 
            text='Select All', 
            width=80,
            command=self._toggle_select_all
        )
        self.select_all_btn.pack(side='left', padx=(0, 5))
        
        # 刷新按钮
        customtkinter.CTkButton(
            self.footer, 
            text='Refresh', 
            width=100,
            command=self.update_data
        ).pack(side='left', padx=(0, 8))
        
        customtkinter.CTkButton(
            self.footer, 
            text='Export to file', 
            width=120,
            command=self._export_all
        ).pack(side='left', padx=(0, 8))
        
        # 刷新库存按钮
        customtkinter.CTkButton(
            self.footer, 
            text='🔄 Refresh Stock', 
            width=120,
            fg_color='#16a085',
            hover_color='#138D75',
            command=self._refresh_stock_display
        ).pack(side='left', padx=(0, 8))
    
    def _hide_batch_operation_bar(self):
        """隐藏批量操作栏"""
        if hasattr(self, 'batch_operation_frame'):
            self.batch_operation_frame.destroy()
        
        # 恢复原始按钮
        for widget in self.footer.winfo_children():
            if widget != self.batch_delete_btn:
                widget.pack_forget()
        
        customtkinter.CTkButton(
            self.footer, 
            text='Refresh', 
            width=100,
            command=self.update_data
        ).pack(side='left', padx=(0, 8))
        
        customtkinter.CTkButton(
            self.footer, 
            text='Export to file', 
            width=120,
            command=self._export_all
        ).pack(side='left', padx=(0, 8))
        
        # 刷新库存按钮
        customtkinter.CTkButton(
            self.footer, 
            text='🔄 Refresh Stock', 
            width=120,
            fg_color='#16a085',
            hover_color='#138D75',
            command=self._refresh_stock_display
        ).pack(side='left', padx=(0, 8))
    
    def _toggle_select_all(self):
        """全选/取消全选"""
        if len(self.selected_orders) == len(self._get_all_order_ids()):
            # 当前全选，则取消全选
            self.selected_orders.clear()
            self.select_all_btn.configure(text='Select All')
        else:
            # 当前未全选，则全选
            self.selected_orders = set(self._get_all_order_ids())
            self.select_all_btn.configure(text='Deselect All')
        
        self._update_selection_display()
        self.update_data()  # 刷新显示
    
    def _get_all_order_ids(self):
        """获取所有订单ID"""
        try:
            if self.controller.auth_service.is_logged_in():
                user_orders = self.controller.order_service.get_user_orders(self.controller.auth_service.current_user.user_id)
            else:
                user_orders = self.controller.order_service.get_all_orders()
            
            order_ids = []
            for order in user_orders:
                if isinstance(order, Order):
                    order_ids.append(order.order_id)
                else:
                    order_id = order.get('order_id', order.get('id', ''))
                    if order_id:
                        order_ids.append(order_id)
            return order_ids
        except:
            return []
    
    def _update_selection_display(self):
        """更新选择状态显示"""
        if hasattr(self, 'selection_label'):
            count = len(self.selected_orders)
            self.selection_label.configure(text=f'Selected: {count} orders')
            
            # 更新确认删除按钮状态
            if hasattr(self, 'confirm_delete_btn'):
                if count > 0:
                    self.confirm_delete_btn.configure(state='normal')
                else:
                    self.confirm_delete_btn.configure(state='disabled')
            
            # 更新批量取消按钮状态
            if hasattr(self, 'confirm_cancel_btn'):
                if count > 0:
                    self.confirm_cancel_btn.configure(state='normal')
                else:
                    self.confirm_cancel_btn.configure(state='disabled')
    
    def _batch_delete_orders(self):
        """批量删除选中的订单"""
        if not self.selected_orders:
            messagebox.showwarning('Tip', 'Please select orders to delete first')
            return
        
        # 确认删除
        count = len(self.selected_orders)
        result = messagebox.askyesno(
            'Confirm Batch Delete', 
            f'Are you sure you want to delete the selected {count} orders?\n\nThis action cannot be undone!'
        )
        if not result:
            return
        
        # 执行批量删除
        success_count = 0
        failed_count = 0
        
        for order_id in list(self.selected_orders):
            try:
                success = self.controller.order_service.delete_order(order_id)
                if success:
                    success_count += 1
                else:
                    failed_count += 1
            except Exception as e:
                failed_count += 1
                from core.utils.logger import error
                error(f"Failed to delete order {order_id}: {e}")
        
        # 显示结果
        if failed_count == 0:
            messagebox.showinfo('Delete Successful', f'Successfully deleted {success_count} orders')
        else:
            messagebox.showwarning(
                'Delete Complete', 
                f'Delete complete: {success_count} succeeded, {failed_count} failed'
            )
        
        # 退出批量删除模式并刷新
        self.batch_delete_mode = False
        self.selected_orders.clear()
        self.batch_delete_btn.configure(text=t('orders.batch_delete.enter_mode'))
        self._hide_batch_operation_bar()
        self.update_data()
    
    def _batch_cancel_orders(self):
        """批量取消选中的订单"""
        if not self.selected_orders:
            messagebox.showwarning('Tip', 'Please select orders to cancel first')
            return
        
        # 获取可取消的订单
        cancellable_orders = self._get_cancellable_orders()
        if not cancellable_orders:
            messagebox.showwarning('Tip', 'No cancellable orders in selection\n\nOnly pending or paid orders can be cancelled')
            return
        
        # 确认取消
        count = len(cancellable_orders)
        result = messagebox.askyesno(
            'Confirm Batch Cancel', 
            f'Are you sure you want to cancel the selected {count} orders?\n\nStock will be automatically restored.'
        )
        if not result:
            return
        
        # 执行批量取消
        success_count = 0
        failed_count = 0
        restored_stock_items = []
        
        for order_id in cancellable_orders:
            try:
                success = self.controller.order_service.cancel_order(order_id)
                if success:
                    success_count += 1
                    # 从选中列表中移除已取消的订单
                    self.selected_orders.discard(order_id)
                else:
                    failed_count += 1
            except Exception as e:
                failed_count += 1
                from core.utils.logger import error
                error(f"Failed to cancel order {order_id}: {e}")
        
        # 显示结果
        if failed_count == 0:
            messagebox.showinfo('Cancel Successful', f'Successfully cancelled {success_count} orders\n\nStock has been automatically restored')
        else:
            messagebox.showwarning(
                'Cancel Complete', 
                f'Cancel complete: {success_count} succeeded, {failed_count} failed\n\nStock has been automatically restored'
            )
        
        # 更新选择状态显示
        self._update_selection_display()
        
        # 刷新页面
        self.update_data()
    
    def _get_cancellable_orders(self):
        """获取可取消的订单ID列表"""
        try:
            if self.controller.auth_service.is_logged_in():
                user_orders = self.controller.order_service.get_user_orders(self.controller.auth_service.current_user.user_id)
            else:
                user_orders = self.controller.order_service.get_all_orders()
            
            cancellable_orders = []
            for order in user_orders:
                if isinstance(order, Order):
                    order_id = order.order_id
                    can_cancel = order.can_cancel()
                else:
                    order_id = order.get('order_id', order.get('id', ''))
                    order_obj = Order.from_dict(order)
                    can_cancel = order_obj.can_cancel()
                
                if order_id in self.selected_orders and can_cancel:
                    cancellable_orders.append(order_id)
            
            return cancellable_orders
        except Exception as e:
            from core.utils.logger import error
            error(f"获取可取消订单失败: {e}")
            return []
    
    def _refresh_stock_display(self):
        """手动刷新库存显示（辅助功能）"""
        try:
            # 获取所有商品并显示库存信息
            products = self.controller.product_service.get_all_products()
            
            if not products:
                messagebox.showinfo('库存信息', '暂无商品数据')
                return
            
            # 创建库存信息窗口
            stock_window = tk.Toplevel(self)
            stock_window.title('商品库存信息')
            stock_window.geometry('700x500')
            stock_window.resizable(True, True)
            
            # 主框架
            main_frame = ttk.Frame(stock_window, padding=10)
            main_frame.pack(fill='both', expand=True)
            
            # 标题
            title_label = customtkinter.CTkLabel(
                main_frame, 
                text='📦 商品库存信息', 
                font=('Arial', 14, 'bold')
            )
            title_label.pack(pady=(0, 10))
            
            # 创建滚动文本框
            text_frame = ttk.Frame(main_frame)
            text_frame.pack(fill='both', expand=True)
            
            text_widget = tk.Text(text_frame, wrap='word', font=('Arial', 10))
            scrollbar = ttk.Scrollbar(text_frame, orient='vertical', command=text_widget.yview)
            text_widget.configure(yscrollcommand=scrollbar.set)
            
            scrollbar.pack(side='right', fill='y')
            text_widget.pack(side='left', fill='both', expand=True)
            
            # 插入库存信息
            text_widget.insert('end', f'刷新时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n\n')
            
            for product in products:
                stock_status = "✅ 充足" if product.stock > 10 else "⚠️ 紧张" if product.stock > 0 else "❌ 缺货"
                text_widget.insert('end', f'• {product.name}\n')
                text_widget.insert('end', f'  库存: {product.stock} 件 {stock_status}\n')
                text_widget.insert('end', f'  价格: ¥{product.price:.2f}\n\n')
            
            text_widget.config(state='disabled')
            
            # 关闭按钮
            customtkinter.CTkButton(
                main_frame, 
                text='关闭', 
                width=100,
                command=stock_window.destroy
            ).pack(pady=10)
            
        except Exception as e:
            from core.utils.logger import error
            error(f"Failed to refresh stock display: {e}")
            messagebox.showerror('Error', f'Failed to refresh stock display: {e}')
